package io.renren.scheduler;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.utils.RedisUtils;
import io.renren.modules.project.entity.BackendEntity;
import io.renren.modules.project.entity.DatasourceEntity;
import io.renren.modules.project.entity.FrontendEntity;
import io.renren.modules.project.entity.ModuleEntity;
import io.renren.modules.project.service.BackendService;
import io.renren.modules.project.service.DatasourceService;
import io.renren.modules.project.service.FrontendService;
import io.renren.modules.project.service.ModuleService;
import io.renren.modules.systemconfig.entity.ServerRuntime;
import io.renren.modules.systemconfig.entity.SystemConfigServersEntity;
import io.renren.modules.systemconfig.service.ProjectBaseService;
import io.renren.modules.systemconfig.service.SysConfigServerService;
import io.renren.ssh.SSHClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.util.List;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class ServerRuntimeDataCollect {

    @Autowired
    private SysConfigServerService sysConfigServerService;
    @Autowired
    private FrontendService frontendService;
    @Autowired
    private ModuleService moduleService;
    @Autowired
    private DatasourceService datasourceService;

    @Autowired
    private RedisUtils redisUtils;

//    @Scheduled(cron = "* 0/2 * * * ?")
//@Scheduled(fixedRate = 1000*60*2)
    private void configureTasks() {
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
        List<SystemConfigServersEntity> servers = sysConfigServerService.list();

        for(SystemConfigServersEntity server:servers){
            if(server.getIpAddr()!=null&&server.getSshPwd()!=null) {
                SSHClient client = null;


                try{
                    client = new SSHClient(server);
                    StringBuffer sb = null;
                    String [] result = null;
                    ServerRuntime rs= new ServerRuntime();
                    try{
                        sb = client.exec("vmstat 1 5 \n");
                        result = sb.toString().split("\n");
                        if(result.length>1){
                            double total = 0d;
                            for(int i = 2 ; i<result.length ;i++){
                                String [] resultList = result[i].trim().split("\\s+");
                                total+=Double.parseDouble(resultList[12]);
                                total+=Double.parseDouble(resultList[13]);
                            }
                            rs.setCpu(total/10);
                        }
                        sb = client.exec("free \n");
                        result = sb.toString().split("\n");
                        if(result.length==3){
                            String [] resultList = result[1].trim().split("\\s+");
                            if(resultList.length==7){
                                rs.setMem(Double.parseDouble(resultList[2])/Double.parseDouble(resultList[1]));
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    try{
                        sb = client.exec("df \n");
                        result = sb.toString().split("\n");
                        if(result.length>1){
                            double total = 0d;
                            double used = 1d;
                            for(int i = 1 ; i<result.length ;i++){
                                String [] resultList = result[i].trim().split("\\s+");
                                total+=Double.parseDouble(resultList[1]);
                                used+=Double.parseDouble(resultList[2]);
                            }
                            rs.setHard(used/total);
                        }

                        sb = client.exec("netstat -na|grep ESTABLISHED|wc -l \n");
                        rs.setConn(sb.toString());

                        redisUtils.set("server-"+ server.getId(), JSONObject.toJSONString(rs), 120);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    try{
                        List<FrontendEntity> fronts = frontendService.getListByServerId(server.getId());
                        for (FrontendEntity front : fronts) {
                            try {
                                int status = HttpRequest.get(front.getAccessAddress()).timeout(3000).execute().getStatus();
                                if (status == 200) {
                                    redisUtils.set("front-" + front.getId(), status, 120);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }


                    try{
                        List<ModuleEntity> modules = moduleService.getListByServerId(server.getId());
                        for(ModuleEntity module : modules){
                            sb = client.exec("ps -ef   |grep "+module.getNameJar()+" |grep -v grep \n");
                            System.out.println("sb:"+sb);
                            result = sb.toString().split("\n");
                            System.out.println("result:"+JSONArray.toJSONString(result));
                            String [] resultList = result[0].trim().split("\\s+");
                            if(resultList.length>1) {
                                redisUtils.set("module-" + module.getId(), JSONArray.toJSONString(resultList), 120);
                            }else{
                                redisUtils.delete("module-" + module.getId());
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    try{
                        List<DatasourceEntity> datasources = datasourceService.getListByServerId(server.getId());
                        for(DatasourceEntity source : datasources){
                            sb = client.exec("ps -ef  |grep "+source.getDatasourceType()+" |grep -v grep \n");
                            System.out.println("sb:"+sb);
                            result = sb.toString().split("\n");
                            System.out.println("result:"+JSONArray.toJSONString(result));
                            String [] resultList = result[0].trim().split("\\s+");
                            if(resultList.length>1) {
                                redisUtils.set("datasource-" + source.getId(), JSONArray.toJSONString(resultList), 120);
                            }else{
                                redisUtils.delete("datasource-" + source.getId());
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if(client!=null)try{
                        client.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
